package com.springboot.pratice.common.config.rsa;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author daisy
 * @date 2021/3/17 14:59
 * Copyright © 2020 ctwing
 */
@Slf4j
@Service("securityService")
public class SecurityUtil {
    private static final String KEY_ALGORITHM = "RSA";
    private static final int KEY_SIZE = 2048;

    @Value("${security.rsa.public-key}")
    private String publicKey;

    @Value("${security.rsa.private-key}")
    private String privateKey;

    /**
     * 随机生成 RSA密钥对
     */
    private static void genKeyPair() {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

        } catch (NoSuchAlgorithmException e) {
            log.error("异常：[{}]", e.getMessage());
            return;
        }
        // 初始化密钥对生成器，密钥大小为96-2048位
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        BASE64Encoder base64 = new BASE64Encoder();
        // 得到公钥字符串
        String publicKeyString = base64.encode(publicKey.getEncoded());
//		String publicKeyString = Base64.encode(publicKey.getEncoded());

        // 得到私钥字符串
        String privateKeyString = base64.encode(privateKey.getEncoded());
//		String privateKeyString = Base64.encode(privateKey.getEncoded());

        log.debug("publicKeyString:\n" + publicKeyString);
        log.debug("==================================================================");
        log.debug("privateKeyString:\n" + privateKeyString);

        ClassPathResource publicKeyResource = new ClassPathResource("rsa_key/publicKey.keystore");
        ClassPathResource privateKeyResource = new ClassPathResource("rsa_key/privateKey.keystore");
        File file;
        FileWriter fileWriter;
        BufferedWriter bufferedWriter;
        try {
            // 将公钥对写入到文件
            file = publicKeyResource.getFile();
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(publicKeyString);
            bufferedWriter.flush();
            // 将私钥对写入到文件
            file = privateKeyResource.getFile();
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(privateKeyString);
            bufferedWriter.flush();

            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            log.error("异常：[{}]", e.getMessage());
        }

    }

    /**
     * 公钥加密过程
     *
     * @param publicKeyStr 公钥
     * @param textData     明文数据
     * @return 返回密文字符串
     * @throws Exception 加密过程中的异常信息
     */
    public String publicKeyEncrypt(String publicKeyStr, String textData) throws Exception {
        if (publicKeyStr == null) {
            throw new Exception("加密公钥为空, 请设置");
        }

        byte[] encPubKey = new BASE64Decoder().decodeBuffer(publicKeyStr);
        // 创建 已编码的公钥规格
        X509EncodedKeySpec encPubKeySpec = new X509EncodedKeySpec(encPubKey);
        // 获取指定算法的密钥工厂, 根据 已编码的公钥规格, 生成公钥对象
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(encPubKeySpec);

        try {
            // 获取指定算法的密码器
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            // 初始化密码器（公钥加密模型）
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(textData.getBytes());
            return new BASE64Encoder().encode(output);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            log.error("异常：[{}]", e.getMessage());
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥加密过程
     *
     * @param privateKeyStr 私钥
     * @param textData      明文数据
     * @return 返回密文字符串
     * @throws Exception 加密过程中的异常信息
     */
    public String privateKeyEncrypt(String privateKeyStr, String textData) throws Exception {
        if (privateKeyStr == null) {
            throw new Exception("加密私钥为空, 请设置");
        }

        byte[] encPriKey = new BASE64Decoder().decodeBuffer(privateKeyStr);
        // 创建 已编码的私钥规格
        PKCS8EncodedKeySpec encPriKeySpec = new PKCS8EncodedKeySpec(encPriKey);
        // 获取指定算法的密钥工厂, 根据 已编码的私钥规格, 生成私钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(encPriKeySpec);

        try {
            // 获取指定算法的密码器
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            // 初始化密码器（私钥加密模型）
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(textData.getBytes());
            return new BASE64Encoder().encode(output);

        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            log.error("异常：[{}]", e.getMessage());
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 公钥解密过程
     *
     * @param publicKeyStr 公钥
     * @param cipherData   密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String publicKeyDecrypt(String publicKeyStr, String cipherData) throws Exception {
        if (publicKeyStr == null) {
            throw new Exception("解密公钥为空，请设置");
        }

        byte[] encPubKey = new BASE64Decoder().decodeBuffer(publicKeyStr);
        // 创建 已编码的公钥规格
        X509EncodedKeySpec encPubKeySpec = new X509EncodedKeySpec(encPubKey);
        // 获取指定算法的密钥工厂, 根据 已编码的公钥规格, 生成公钥对象
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(encPubKeySpec);

        try {
            // 使用默认RSA
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(new BASE64Decoder().decodeBuffer(cipherData));
            return new String(output);

        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            log.error("异常：[{}]", e.getMessage());
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密公钥非法，请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 私钥解密过程
     *
     * @param privateKeyStr 私钥
     * @param cipherData    密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public String privateKeyDecrypt(String privateKeyStr, String cipherData) throws Exception {
        if (privateKeyStr == null) {
            throw new Exception("解密私钥为空，请设置");
        }

        byte[] encPriKey = new BASE64Decoder().decodeBuffer(privateKeyStr);
        // 创建 已编码的私钥规格
        PKCS8EncodedKeySpec encPriKeySpec = new PKCS8EncodedKeySpec(encPriKey);
        // 获取指定算法的密钥工厂, 根据 已编码的私钥规格, 生成私钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(encPriKeySpec);

        try {
            // 使用默认RSA
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(new BASE64Decoder().decodeBuffer(cipherData));
            return new String(output);

        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            log.error("异常：[{}]", e.getMessage());
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法，请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }
}
